package com.zgh.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.zgh.domain.BbsCollection;
import com.zgh.domain.Result;
import com.zgh.domain.User;
import com.zgh.domain.ipageUser;
import com.zgh.domain.UserCollection;
import com.zgh.mapper.BbsCommentMapper;
import com.zgh.service.*;
import com.zgh.util.HttpClientUtil;
import com.zgh.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/my")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private BlogService blogService;

    @Autowired
    private BbsCommentService bbsCommentService;

    @Autowired
    private BlogCommentService blogCommentService;

    @Autowired
    private BbsService bbsService;

    @Value("${wechat.appid}")
    private String appid;
    @Value("${wechat.appsecret}")
    private String appsecret;

    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public Result login(@RequestBody String code, HttpServletRequest request){
        // code
        String code1 = JSON.parseObject(code).getString("code");
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret=" + appsecret + "&js_code=" + code1 + "&grant_type=authorization_code";
        //System.out.println(code1);
        String resultString = HttpClientUtil.doPost(url);
        JSONObject SessionKeyOpenId = (JSONObject)JSONObject.parse(resultString);
        //System.out.println(SessionKeyOpenId);
        String openid = SessionKeyOpenId.getString("openid");
        String sessionKey = SessionKeyOpenId.getString("session_key");
        System.out.println(sessionKey);
        System.out.println(openid);
        //判断当前用户是否存在
        User user= userService.findByOpenId(openid);
        if (user==null){
            return new Result(false,"用户不存在",openid);
        }else {
            Map<String,String> map = new HashMap<>();
            map.put("openId",user.getOpenid());
            map.put("nickname",user.getNickname());
            String hs_token = JwtUtil.getToken(map);
            //System.out.println(hs_token);
            Map<String,Object> map1 = new HashMap<>();
            Map<String,Object> map2 = new HashMap<>();
            map2.put("openId",user.getOpenid());
            map2.put("nickname",user.getNickname());
            map2.put("avatar",user.getHeadPortrait());
            map1.put("hs_token",hs_token);
            map1.put("sessionKey",sessionKey);
            map1.put("user",map2);
            return new Result(true,"登录成功",map1);
        }
    }

    @RequestMapping(value = "/register",method = RequestMethod.POST)
    public Result register(@RequestBody String user){
        User user1 = new User();
        //System.out.println(user);
        user1.setLevel(0);
        user1.setNickname(JSON.parseObject(user).getString("nickName"));
        user1.setHeadPortrait(JSON.parseObject(user).getString("avatar"));
        user1.setOpenid(JSON.parseObject(user).getString("openid"));
        int count = userService.register(user1);
        if (count==1){
            return new Result(true,"注册成功",null);
        }else {
            return new Result(false, "注册失败", null);
        }
    }

    @RequestMapping(value = "/saveInfo",method = RequestMethod.POST)
    public Result saveUserInfo(@RequestBody String user){
        User user1 = new User();
        user1.setArea(JSON.parseObject(user).getString("area"));
        user1.setPhone(JSON.parseObject(user).getString("phone"));
        user1.setAge(JSON.parseObject(user).getInteger("age"));
        user1.setOpenid(JSON.parseObject(user).getString("openid"));
        int count = userService.saveUserInfo(user1);
        if (count==1){
            return new Result(true,"保存成功",null);
        }else {
            return new Result(false, "保存失败", null);
        }
    }

    @RequestMapping(value = "/getUserInfo",method = RequestMethod.POST)
    public Result getUserInfo(@RequestBody String openidStr){
        String openid = JSON.parseObject(openidStr).getString("openid");
        User user = userService.findByOpenId(openid);
        if (user!=null){
            return new Result(true,"获取成功",user);
        }else {
            return new Result(false, "获取失败", null);
        }
    }

    //用户收藏论坛
    @RequestMapping(value = "/collectBbs",method = RequestMethod.POST)
    public Result collectBbs(@RequestBody String params){
        //System.out.println(params);
        String bbsId = JSON.parseObject(params).getString("bbsId");
        String openId = JSON.parseObject(params).getString("openId");
        String operator = JSON.parseObject(params).getString("operator");
        //收藏
        bbsService.collect(bbsId,openId,operator);
        if ("0".equals(operator)){
            return new Result(true,"收藏成功",null);
        }else{
            return new Result(true,"取消收藏成功",null);
        }
    }

    //判断当前用户的收藏论坛列表
    @RequestMapping(value = "/isCollectBbs/{openId}",method = RequestMethod.GET)
    public Result collectBbsList(@PathVariable String openId){
        List<BbsCollection> bbsCollectionList = bbsService.getBbsCollectList(openId);
        if(bbsCollectionList!=null){
            return new Result(true,"查询成功",bbsCollectionList);
        }else{
            return new Result(false,"查询失败",null);
        }
    }

    //评论论坛
    @RequestMapping(value = "/sendComment",method = RequestMethod.POST)
    public Result comment(@RequestBody String comments){
        //System.out.println(comments);
        String comment = JSON.parseObject(comments).getString("comment");
        String openId = JSON.parseObject(comments).getString("userId");
        String bbsId = JSON.parseObject(comments).getString("bbsId");
        int count = bbsCommentService.sendComment(comment,openId,bbsId);
        if (count==1){
            return new Result(true,"发布成功",null);
        }else{
            return new Result(false,"发布失败",null);
        }
    }

    //用户收藏博客
    @RequestMapping(value = "/collectBlog",method = RequestMethod.POST)
    public Result collectBlog(@RequestBody String params){
        //System.out.println(params);
        String blogId = JSON.parseObject(params).getString("blogId");
        String openId = JSON.parseObject(params).getString("openId");
        String operator = JSON.parseObject(params).getString("operator");
        //收藏
        blogService.collect(blogId,openId,operator);
        if ("0".equals(operator)){
            return new Result(true,"收藏成功",null);
        }else{
            return new Result(true,"取消收藏成功",null);
        }
    }


    //判断当前用户的收藏博客列表
    @RequestMapping(value = "/isCollectBlog/{openId}",method = RequestMethod.GET)
    public Result collectBlogList(@PathVariable String openId){
        List<UserCollection> blogCollectionList = blogService.getBlogCollectList(openId);
        if(blogCollectionList!=null){
            return new Result(true,"查询成功",blogCollectionList);
        }else{
            return new Result(false,"查询失败",null);
        }
    }

    //评论播客
    @RequestMapping(value = "/sendBlogComment",method = RequestMethod.POST)
    public Result blogComment(@RequestBody String comments){
        //System.out.println(comments);
        String comment = JSON.parseObject(comments).getString("comment");
        String openId = JSON.parseObject(comments).getString("userId");
        String blogId = JSON.parseObject(comments).getString("blogId");
        int count = blogCommentService.sendComment(comment,openId,blogId);
        if (count==1){
            return new Result(true,"发布成功",null);
        }else{
            return new Result(false,"发布失败",null);
        }
    }
    //管理员登录

    @RequestMapping(value = "/mannerLogin",method = RequestMethod.POST)
    public Result mannerLogin(@RequestBody String userInfo){
        //System.out.println(userInfo);
        String username = JSON.parseObject(userInfo).getString("username");
        String password = JSON.parseObject(userInfo).getString("password");
        User user = userService.mannerLogin(username,password);

        if (user!=null){
            Map<String,String> map = new HashMap<>();
            //用时间戳拼接返回token的secret
            String secret = String.valueOf(System.currentTimeMillis());
            map.put("openId", secret);
            String token = JwtUtil.getToken(map);
            String id = String.valueOf(user.getId());
            ArrayList<String> info = new ArrayList<>();
            info.add(token);
            info.add(id);
            return new Result(true,"登录成功",info);
        }else{
            return new Result(false,"登录失败",null);
        }
    }

    // 分页查询
    @RequestMapping(value = "/getAllUserInfo",method = RequestMethod.POST)
    public Result getAllUserInfo(@RequestBody String condition){
    //System.out.println(JSON.parseObject(condition));
        String query = JSON.parseObject(condition).getString("query");
        int pagenum = JSON.parseObject(condition).getInteger("pagenum");
        int pagesize = JSON.parseObject(condition).getInteger("pagesize");
        System.out.println(pagesize);

        ipageUser ipageUser = userService.getAllUserInfo(pagenum,pagesize,query);
    System.out.println(ipageUser);
        if (ipageUser!=null){
            return new Result(true,"获取用户列表成功",ipageUser);
        }else {
            return new Result(false, "获取用户列表失败", null);
        }
    }

    //添加管理员
    @RequestMapping(value = "/addAdmin",method = RequestMethod.POST)
    public Result addAdmin(@RequestBody String user){
        User user1 = new User();
        user1.setLevel(JSON.parseObject(user).getInteger("level"));
        user1.setNickname(JSON.parseObject(user).getString("username"));
        user1.setPhone(JSON.parseObject(user).getString("mobile"));
        user1.setPassword(JSON.parseObject(user).getString("password"));
        int count = userService.register(user1);
        if (count==1){
            return new Result(true,"添加成功",null);
        }else {
            return new Result(false, "添加失败", null);
        }
    }

    // 保存用户信息
    @RequestMapping(value = "/saveInfoByid",method = RequestMethod.POST)
    public Result saveInfoByid(@RequestBody String user){
        User user1 = new User();
        user1.setArea(JSON.parseObject(user).getString("area"));
        user1.setPhone(JSON.parseObject(user).getString("phone"));
        user1.setAge(JSON.parseObject(user).getInteger("age"));
        user1.setId(JSON.parseObject(user).getInteger("id"));
        //user1.setLevel(JSON.parseObject(user).getInteger("level"));
        int count = userService.saveInfoByid(user1);
        if (count==1){
            return new Result(true,"保存成功",null);
        }else {
            return new Result(false, "保存失败", null);
        }
    }

    // 通过id 获取用户信息
    @RequestMapping(value = "/getInfoByid",method = RequestMethod.POST)
    public Result getUserInfoByid(@RequestBody String idStr){
        Integer id = JSON.parseObject(idStr).getInteger("id");
        User user = userService.findById(id);
        if (user!=null){
            return new Result(true,"获取成功",user);
        }else {
            return new Result(false, "获取失败", null);
        }
    }

    // 通过id 删除用户信息
    @RequestMapping(value = "/deleteByid",method = RequestMethod.POST)
    public Result deleteByid(@RequestBody String idStr){
        Integer id = JSON.parseObject(idStr).getInteger("id");
        int count = userService.deleteByid(id);
        if (count!=0){
            return new Result(true,"删除成功",null);
        }else {
            return new Result(false, "删除失败", null);
        }
    }

    // 通过id 获取用户信息
    @RequestMapping(value = "/findUserById/{id}",method = RequestMethod.GET)
    public Result findUserById(@PathVariable String id){
        User user = userService.findById(Integer.parseInt(id));
        if (user!=null){
            return new Result(true,"获取成功",user);
        }else {
            return new Result(false, "获取失败", null);
        }
    }
}
